package com.metadata_system.common.utils;

public class Base62Encoder {
    private static final String BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    /**
     * 将 10 进制数字转换为 62 进制字符串
     * @param num 10 进制数字（必须 ≥ 0）
     * @return 62 进制字符串
     */
    public static String encode(long num) {
        if (num == 0) {
            return "0";
        }
        StringBuilder sb = new StringBuilder();
        while (num > 0) {
            int remainder = (int) (num % 62);
            sb.append(BASE62_CHARS.charAt(remainder));
            num /= 62;
        }
        return sb.reverse().toString();
    }

    /**
     * 将 62 进制字符串转换回 10 进制数字
     * @param str 62 进制字符串
     * @return 10 进制数字
     */
    public static long decode(String str) {
        long num = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int value = BASE62_CHARS.indexOf(c);
            num = num * 62 + value;
        }
        return num;
    }

    public static void main(String[] args) {
        long num = 1234567890L;
        String encoded = encode(num);
        long decoded = decode(encoded);

        System.out.println("原始数字: " + num);
        System.out.println("62 进制编码: " + encoded);
        System.out.println("解码回 10 进制: " + decoded);
    }

    /**
     * 生成 62 进制唯一标识
     * @return 62 进制唯一标识
     */
    public static String generateUniqueKey() {
        return encode(System.currentTimeMillis());
    }
}
